// 蛇形转驼峰
export function snakeToCamel(str: string): string {
  if (str.indexOf('_') > -1) {
    str = str.replace(/_(\w)/g, ($0, $1) => {
      return $1.toUpperCase();
    });
  }
  return str;
}
// 驼峰转蛇形
export function cameToSnake(str: string): string {
  return str.replace(/([^A-Z])([A-Z])/g, function ($0, $1, $2) {
    return $1 + '_' + $2.toLowerCase();
  });
}

// 首字母转大写
export function uppercaseFirst(str: string): string {
  if (!str) return str;
  return str.charAt(0).toUpperCase() + str.slice(1);
}

// 首字母转小写
export function lowercaseFirst(str: string): string {
  if (!str) return str;
  return str.charAt(0).toLowerCase() + str.slice(1);
}

// 获取字符串字节长度
export function getByteLength(str: string): number {
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

// 字符串左侧填充字符
export function padStart(str: string, length: number, chars: string): string {
  const strLength = String(str).length;
  const targetLength = Math.max(length, 0);
  if (targetLength <= strLength) return str;
  const padLength = targetLength - strLength;
  let padding = '';
  if (chars) {
    const repeatCount = Math.ceil(padLength / chars.length);
    padding = chars.repeat(repeatCount).slice(0, padLength);
  }
  return padding + str;
}

// 字符串左侧填充字符
export function padEnd(str: string, length: number, chars: string): string {
  const strLength = String(str).length;
  const targetLength = Math.max(length, 0);
  if (targetLength <= strLength) return str;
  const padLength = targetLength - strLength;
  let padding = '';
  if (chars) {
    const repeatCount = Math.ceil(padLength / chars.length);
    padding = chars.repeat(repeatCount).slice(0, padLength);
  }
  return str + padding;
}

// 替换字符串区间
export function replaceRange(str: string, start: number, end: number, replacement: string): string {
  return str.substring(0, start) + replacement + str.substring(end);
}

// 固定长度插入字符
export function insertByLength(str: string, len = 4, separator = ' '): string {
  const regex = new RegExp(`.{${len}}`, 'g');
  return `${str}`.replace(regex, ($0) => `${$0}${separator}`);
}

// 影藏部分手机号码
export function maskPhoneNumber(str: string): string {
  return replaceRange(str, 3, 7, '****');
}

// 金额千分位逗号分隔
export function formatAmount(value: string | number): string {
  const regex = new RegExp('\\B(?=(\\d{3})+(?!\\d))', 'g');
  return `${value}`.replace(regex, ',');
}

// 获取字符串后缀
export function getStringSuffix(str: string, separator = '.'): string {
  const parts = str.split(separator);
  return parts[parts.length - 1];
}
